import { KeyboardEvent, MouseEvent } from "./event";
import { TextModel, SelectionModel } from "./models";
import {
  InsertTextOperation,
  SetSelectionOperation,
  RemoveTextOperation,
} from "./operations";
import { ViewProvider } from "./view";

export class Editor {
  textModel_;
  KeyboardEvent_;
  selectionModel_;
  view_;
  eventHandler;
  config_ = {
    mode: "sourceAndPreview",
  };
  constructor(container) {
    this.container = container;
  }
  init() {
    this.textModel_ = new TextModel();
    this.selectionModel_ = new SelectionModel();
    // this.view_ = new RenderView(
    //   this.textModel_,
    //   this.selectionModel_,
    //   this.container
    // );
    this.view_ = new ViewProvider().provider(this.config_.mode, this);

    this.eventHandler = new KeyboardEvent(this, this.container, this.view_);
    // this.mouseEventHandler = new MouseEvent(this, this.container, this.view_);
    this.eventHandler.addListeners();
    // this.mouseEventHandler.addListeners();
  }
  apply(operations) {
    operations.apply(this);
  }
  getTextModel() {
    return this.textModel_;
  }
  getSelectionModel() {
    return this.selectionModel_;
  }
  getEditorContainer() {
    return this.container;
  }
  setSelection(anchor, focus) {
    const selectionOperaction = new SetSelectionOperation({ anchor, focus });
    this.apply(selectionOperaction);
  }

  insertTextAtCursor(text) {
    // 获取选区，看他是否有选区，区分2种操作一种选区替换文字，一种尾部插入
    const selection = this.selectionModel_.getSelection();
    let startIndex = selection.anchor;
    let cursorIndex;
    if (!this.selectionModel_.isCollapsed()) {
    } else {
      cursorIndex = startIndex + text.length;
      const insertTextOperation = new InsertTextOperation(text, startIndex);
      this.apply(insertTextOperation);
      this.setSelection(cursorIndex, cursorIndex);
    }

    // this.textModel_.insertText
  }
  deleteTextAtCursor() {
    const selection = this.selectionModel_.getSelection();
    let startIndex = selection.anchor;
    let deleteTextOperation;
    if (!this.selectionModel_.isCollapsed()) {
      deleteTextOperation = new RemoveTextOperation(
        selection.anchor,
        selection.focus
      );
      if (this.selectionModel_.isBackward()) {
        startIndex = selection.focus;
      }
    } else if (selection.anchor > 0) {
      deleteTextOperation = new RemoveTextOperation(
        selection.anchor - 1,
        selection.focus
      );
      startIndex--;
    }
    this.apply(deleteTextOperation);
    this.setSelection(startIndex, startIndex);
  }
  // 更改视图模式
  changeRenderSourceAndPreview() {
    if (this.config_.mode === "sourceAndPreview") {
      return;
    }
    this.view_ = new ViewProvider().provider(
      (this.config_.mode = "sourceAndPreview"),
      this
    );
  }
}

export default Editor;
